//
//  HKURLResponse.m
//  HKNetService
//
//  Created by 胡锦涛 on 2018/6/12.
//  Copyright © 2018年 胡锦涛. All rights reserved.
//

#import "HKURLResponse.h"
#import "HKNetWorkConfig.h"
#import <dlfcn.h>
#import "HTTPDNSCookieManager.h"

typedef CFHTTPMessageRef (*MYURLResponseGetHTTPResponse)(CFURLRef response);

@interface HKURLResponse ()
@property (nonatomic, assign, readwrite)HKResponseStatus status;
@property (nonatomic, assign, readwrite)NSInteger requestId;
@property (nonatomic, strong, readwrite)NSURLSessionDataTask *task;
@property (nonatomic, copy, readwrite)id responseData;
@property (nonatomic, copy, readwrite) id result;
@property (nonatomic, assign, readwrite) BOOL isCache;
@end

@implementation HKURLResponse
-(instancetype)initWithSessionDataTask:(NSURLSessionDataTask *)task requestParams:(NSDictionary *)requestParams responseData:(id)responseData status:(HKResponseStatus)status
{
    self = [super init];
    if (self) {
        
        if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
            
            NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
            
            [[HTTPDNSCookieManager sharedInstance] handleHeaderFields:[httpResponse allHeaderFields] forURL:httpResponse.URL];
            
            NSDictionary *headers = [httpResponse allHeaderFields];
            
#if HK_SHOW_REQUESTHEAD_INFO
            
            [self getHTTPVersion:task.response];
            
            NSLog(@"statusCode:%d", (int)[httpResponse statusCode]);
            //        NSDictionary *headers = [httpResponse allHeaderFields];
            NSEnumerator * keys = [headers keyEnumerator];
            NSString *key;
            while (key=[keys nextObject]) {
                NSLog(@"[response]%@=%@",key, [headers valueForKey:key]);
            }
            NSLog(@"expectedContentLength:%lld", [task.response expectedContentLength]);
#endif
    
            NSString *SetCookie = [headers valueForKey:@"Set-Cookie"];
            if ([SetCookie length] && [SetCookie containsString:@"XBSESSIONID"]) {
                
                NSRange range = [SetCookie rangeOfString:@"XBSESSIONID="];
                NSRange range1 = [SetCookie rangeOfString:@";" options:1 range:NSMakeRange(range.location, SetCookie.length-range.location)];
                NSString *cookie = [SetCookie substringWithRange:NSMakeRange(range.location, range1.location-range.location)];
                NSLog(@"setcookie %@ ----------------%@",task.response.URL,cookie);
            }
        }
        
        self.task = task;
        
        NSError *error;
        
        id data = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
        if (error) {
            NSLog(@"json error");
        }
        self.result = data[@"result"];
        self.responseData = data?data:responseData;
        self.status = status;
        self.requestParams = requestParams;
        self.isCache = NO;
    }
    
    return self;
}

-(instancetype)initWithSessionDataTask:(NSURLSessionDataTask *)task requestParams:(NSDictionary *)requestParams responseData:(id)responseData error:(NSError *)error
{
    if (self = [super init]) {
        self.task = task;
        self.status = [self responseStatusWithError:error];
        self.requestParams = requestParams;
        if (responseData) {
            NSError *error;
            id data = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
            if (error) {
                NSLog(@"json error");
            }
            self.result = data[@"result"];
            self.responseData = data?data:responseData;
        } else {
            self.result = nil;
            self.responseData = nil;
        }
        self.isCache = NO;
    }
    
    return self;
}
- (instancetype)initWithData:(NSData *)data
{
    self = [super init];
    if (self) {
        self.task = nil;
        self.status = [self responseStatusWithError:nil];
        self.requestId = 0;
        id resData;
        if ([data isKindOfClass:[NSDictionary class]]) {
            resData = data;
        }else{
            resData = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        }
        self.result = resData[@"result"];
        self.responseData = resData?resData:data;
        self.isCache = YES;
    }
    
    return self;
}
#pragma mark - private methods

-(void)getHTTPVersion:(NSURLResponse *)res {
    NSURLResponse *response = res;
    NSString *version;
    NSString *funName = @"CFURLResponseGetHTTPResponse";
    MYURLResponseGetHTTPResponse originURLResponseGetHTTPResponse =
    dlsym(RTLD_DEFAULT, [funName UTF8String]);
    SEL theSelector = NSSelectorFromString(@"_CFURLResponse");
    if ([response respondsToSelector:theSelector] &&
        NULL != originURLResponseGetHTTPResponse) {
        CFTypeRef cfResponse = CFBridgingRetain([response performSelector:theSelector]);
        if (NULL != cfResponse) {
            
            CFHTTPMessageRef message = originURLResponseGetHTTPResponse(cfResponse);
            
            CFStringRef cfVersion = CFHTTPMessageCopyVersion(message);
            if (NULL != cfVersion) {
                version = (__bridge NSString *)cfVersion;
                CFRelease(cfVersion);
            }
            CFRelease(cfResponse);
        }
    }
    
    if (nil == version || 0 == version.length) {
        version = @"获取失败";
    }
    NSLog(@"HTTPVersion : %@",version);
}
- (HKResponseStatus)responseStatusWithError:(NSError *)error
{
    if (error) {
        HKResponseStatus result = HKResponseStatusErrorNoNetwork;
        // 除了超时以外，所有错误都当成是无网络
        if (error.code == NSURLErrorTimedOut) {
            result = HKResponseStatusErrorTimeout;
        }
        return result;
    } else {
        return HKResponseStatusSuccess;
    }
}

-(id)result{
    if ([_result isKindOfClass:[NSString class]]) {
        if ([(NSString *)_result length]) {
            return _result;
        }
        return nil;
    }else if ([_result isKindOfClass:[NSNull class]]){
        return nil;
    }else if ([_result isKindOfClass:[NSArray class]]){
        
        NSMutableArray *a = [(NSArray *)_result mutableCopy];
        for (int i =0 ; i<a.count; i++) {
            if ([a[i] isKindOfClass:[NSNull class]]) {
                [a replaceObjectAtIndex:i withObject:@{}];
            }
        }
        return a;
    }
    return _result;
}

@end
